package com.rongshu.view.home.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.App;
import com.rongshu.R;
import com.rongshu.eventbus.NavigationIconReplace;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.DateUtils;
import com.rongshu.utils.FileUtils;
import com.rongshu.utils.GlideUtils;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.home.activity.DaySignListActivity;
import com.rongshu.view.home.activity.EditDaySignActivity;
import com.rongshu.view.home.activity.MoreArticleDetailsActivity;
import com.rongshu.view.home.activity.PreviewImgActivity;
import com.rongshu.view.home.activity.ShareDaySignActivity;
import com.rongshu.view.home.adapter.TodayRecommendListAdapter;
import com.rongshu.view.home.contract.TodayRecommendView;
import com.rongshu.view.home.entity.ArticleItem;
import com.rongshu.view.home.entity.DaySignInfo;
import com.rongshu.view.home.listener.OnTodayRecommendListener;
import com.rongshu.view.home.presenter.TodayRecommendPresenter;
import com.rongshu.view.home.widget.SelectableTextView;
import com.rongshu.widget.YNestedScrollView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utils.DensityUtil;
import com.utils.FastClickUtils;
import com.utils.NetStatusUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.rongshu.utils.UserInfoUtils.getUserId;

public class TodayRecommendFragment extends BaseFragment<TodayRecommendPresenter> implements TodayRecommendView {
    @BindView(R.id.layout_day_sign_bg)
    RelativeLayout layout_day_sign_bg;
    @BindView(R.id.layout_data)
    RelativeLayout layout_data;
    @BindView(R.id.layout_content)
    RelativeLayout layout_content;
    @BindView(R.id.iv_day_sign_img)
    ImageView iv_day_sign_img;
    @BindView(R.id.txt_day_sign_title)
    TextView txt_day_sign_title;
    @BindView(R.id.top_layout)
    LinearLayout top_layout;
    @BindView(R.id.date_content)
    TextView date_content;
    @BindView(R.id.txt_share_data)
    TextView txt_share_data;
    @BindView(R.id.txt_day_sign_identification)
    TextView txt_day_sign_identification;
    @BindView(R.id.iv_white_data)
    ImageView iv_white_data;
    @BindView(R.id.iv_black_data)
    ImageView iv_black_data;
    @BindView(R.id.layout_today_title)
    LinearLayout layout_today_title;
    @BindView(R.id.txt_day_sign_top)
    TextView txt_day_sign_top;
    @BindView(R.id.txt_day_sign_top_title)
    TextView txt_day_sign_top_title;
    @BindView(R.id.iv_day_sign)
    ImageView iv_day_sign;
    @BindView(R.id.txt_sign_ahthor)
    TextView txt_sign_ahthor;
    @BindView(R.id.iv_edit)
    ImageView iv_edit;
    @BindView(R.id.iv_share)
    ImageView iv_share;
    @BindView(R.id.praise_layout)
    RelativeLayout praise_layout;
    @BindView(R.id.iv_praise)
    ImageView iv_praise;
    @BindView(R.id.praise_num)
    TextView praise_num;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.nested_scroll_view)
    YNestedScrollView nested_scroll_view;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.materialHeader)
    MaterialHeader materialHeader;
    @BindView(R.id.txt_day_sign_content)
    SelectableTextView txt_day_sign_content;
    @BindView(R.id.layout_no_network)
    RelativeLayout layout_no_network;
    @BindView(R.id.txt_refresh_page)
    TextView txt_refresh_page;

    //状态栏高度
    private int toolbarHeight;
    //adapter
    private TodayRecommendListAdapter todayAdapter = null;
    //list
    private List<ArticleItem> mArticleItemList = null;
    //manager
    private LinearLayoutManager manager = null;
    //pageIndex
    private int pageIndex = 1;
    //pageSize
    private int pageSize = 10;
    //isLoadMore
    private boolean isLoadMore = false;
    //第一次进入
    private boolean isFirstEnter = true;
    //是否头部刷新
    private boolean isHeaderRefresh = false;
    //今日推荐位置
    private int topLocation = 0;
    //intent
    private Intent intent = null;
    //map
    private Map<String, Object> map = null;
    //日签
    private DaySignInfo.ResponseBean signInfo = null;
    //requestCode
    private final int REQUEST_CODE = 0X0A;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_recommend_view;
    }

    @Override
    protected void initViews() {
        setPresenter(new TodayRecommendPresenter(getActivity()), this);
        //状态栏高度
        toolbarHeight = DensityUtil.getStateBar(getActivity());
        //初始化
        initCoordinatorMenu();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        getDaySign();
        getAtricleDetails();
    }

    /**
     * 获取首页日签
     */
    private void getDaySign() {
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getDaySign(
                (int) map.get("user_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 请求文章
     */
    public void getAtricleDetails() {
        if (!NetStatusUtils.isConnected(getActivity())) {
            layout_no_network.setVisibility(View.VISIBLE);
            toast("网络不给力");
            return;
        } else {
            layout_no_network.setVisibility(View.GONE);
            if (getActivity() != null && pageIndex == 1 && !isHeaderRefresh) {
                ((BaseActivity) getActivity()).showLoading(true, isFirstEnter);
            }
        }
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getArticleDetails(
                (int) map.get("user_id"),
                (int) map.get("pageIndex"),
                (int) map.get("pageSize"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 日签点赞
     */
    private void getDaySignLike(int dailyCheckId, int type) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(getContext());
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("dailyCheckId", dailyCheckId);
        map.put("type", type);
        presenter.getDaySignLike(
                (int) map.get("user_id"),
                (int) map.get("dailyCheckId"),
                (int) map.get("type"),
                Common.encryptionSign(map));
        map.clear();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE://多个文章返回
                    if (data == null) {
                        return;
                    }
                    mArticleItemList = App.getApplication().getList();
                    pageIndex = data.getIntExtra(Constant.INTENT_PAGEINDEX, pageIndex);
                    todayAdapter.setArticleItemList(mArticleItemList);
                    todayAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @OnClick({R.id.iv_praise, R.id.iv_day_sign, R.id.iv_share, R.id.iv_edit,
            R.id.layout_day_sign_bg, R.id.top_layout, R.id.txt_refresh_page})
    public void onClcik(View view) {
        switch (view.getId()) {
            case R.id.iv_day_sign://日签
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (UserInfoUtils.getUserInfo() != null) {
                    intent = new Intent(getActivity(), DaySignListActivity.class);
                    startActivity(intent);
                } else {
                    LoginUtils.toLogin(getActivity());
                }
                break;
            case R.id.iv_praise://点赞
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (signInfo != null) {
                    getDaySignLike(signInfo.getId(), signInfo.getIsLike() == 0 ? 1 : 0);
                }
                break;
            case R.id.iv_share://分享
                if (!FastClickUtils.isFastClick() && signInfo != null) {
                    intent = new Intent(getActivity(), ShareDaySignActivity.class);
                    signInfo.setIsSystem(Constant.DAY_SIGN_RONGSHU);
                    intent.putExtra(Constant.INTENT_DATA, signInfo);
                    startActivity(intent);
                }
                break;
            case R.id.iv_edit://编辑
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (signInfo == null) {
                    return;
                }
                if (UserInfoUtils.getUserInfo() == null) {
                    LoginUtils.toLogin(getActivity());
                    return;
                }
                intent = new Intent(getActivity(), EditDaySignActivity.class);
                intent.putExtra(Constant.INTENT_TYPE, Constant.DAY_SIGN_RONGSHU);
                intent.putExtra(Constant.INTENT_DATA, signInfo.getId());
                startActivity(intent);
                break;
            case R.id.layout_day_sign_bg://日签图片查看
                if (FastClickUtils.isFastClick() || signInfo == null) {
                    return;
                }
                ArrayList<String> list = new ArrayList<>();
                list.add(signInfo.getImgUrl());
                intent = new Intent(getActivity(), PreviewImgActivity.class);
                intent.putStringArrayListExtra(Constant.INTENT_DATA, list);
                startActivity(intent);
                break;
            case R.id.top_layout://topLayout
                nested_scroll_view.fullScroll(NestedScrollView.FOCUS_UP);
                break;
            case R.id.txt_refresh_page:
                updateViews(false);
                break;
        }
    }

    /**
     * 刷新
     */
    public void refreshTodayRecommend(boolean isTopRefresh) {
        pageIndex = 1;
        isHeaderRefresh = isTopRefresh;
        isLoadMore = false;
        getAtricleDetails();
    }

    /**
     * 初始化
     */
    private void initCoordinatorMenu() {
        top_layout.getBackground().setAlpha(0);
        final ViewTreeObserver observer = top_layout.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (observer.isAlive()) {
                    observer.removeOnGlobalLayoutListener(this);
                }
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) top_layout.getLayoutParams();
                lp.height = (int) (getResources().getDimension(R.dimen.dd_dimen_120px) + toolbarHeight);
                top_layout.setLayoutParams(lp);
            }
        });
        //adapter
        todayAdapter = new TodayRecommendListAdapter(getActivity());
        mArticleItemList = new ArrayList<>();
        todayAdapter.setArticleItemList(mArticleItemList);
        //recyclerview
        manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setFocusable(false);
        recyclerView.setFocusableInTouchMode(false);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(todayAdapter);
        //header
        materialHeader.setColorSchemeColors(getResources().getColor(R.color.color_3cc051));
        //listener
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshTodayRecommend(true);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
                isLoadMore = true;
                getAtricleDetails();
                refreshLayout.finishLoadmore(5000, true);
            }
        });
        //adapter
        todayAdapter.setOnTodayRecommendListener(new OnTodayRecommendListener() {
            @Override
            public void onItemClick(int position) {
                intent = new Intent(getActivity(), MoreArticleDetailsActivity.class);
                App.getApplication().setList(mArticleItemList);
                intent.putExtra(Constant.INTENT_PAGEINDEX, pageIndex);
                intent.putExtra(Constant.INTENT_POSITION, position);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });
        //nested_scroll_view
        nested_scroll_view.setOnScrollChangeListener(new YNestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(YNestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                mScrollY = scrollY;
                isSildeDown = scrollY > oldScrollY;
                int location = layout_content.getTop() - top_layout.getHeight();
                if (scrollY < location) {//渐变成白色
                    if (scrollY == 0) {
                        top_layout.getBackground().setAlpha(0);
                        return;
                    }
                    int alpha = (int) ((scrollY / Float.valueOf(location)) * 255);
                    top_layout.getBackground().setAlpha(alpha);
                    iv_day_sign.setImageResource(R.drawable.sign_day_border_icon);
                } else {
                    top_layout.getBackground().setAlpha(255);
                    iv_day_sign.setImageResource(R.drawable.sign_day_icon);
                }
                //今日推荐
                topLocation = layout_today_title.getTop() + txt_day_sign_top.getBottom() - top_layout.getMeasuredHeight();
                if (topLocation <= scrollY) {
                    txt_day_sign_top_title.setVisibility(View.VISIBLE);
                } else {
                    txt_day_sign_top_title.setVisibility(View.GONE);
                }
                //首页icon替换
                int childSevenTop = manager.findViewByPosition(6).getBottom() + recyclerView.getTop()
                        + layout_today_title.getTop() - nested_scroll_view.getMeasuredHeight();
                EventBus.getDefault().post(new NavigationIconReplace(scrollY >= childSevenTop));
            }
        });
        nested_scroll_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        isActionUp = false;
                        mHandler.removeCallbacksAndMessages(null);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (topLocation >= mScrollY) {
                            isActionUp = true;
                            mHandler.sendEmptyMessageDelayed(REQUESTCODE, 100);
                        }
                        break;
                }
                return false;
            }
        });
    }

    //scrollY
    private int mScrollY = 0;
    //滑动方向
    private boolean isSildeDown = false;
    //是否手放开
    public boolean isActionUp = false;
    //标识
    private final int REQUESTCODE = 0x01;

    /**
     * Hander检查NestScrollView滑动停止
     */
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REQUESTCODE:
                    mHandler.removeMessages(REQUESTCODE);
                    if (mScrollY < layout_today_title.getTop()) {
                        if (mScrollY == nested_scroll_view.getScrollY() && isActionUp) {
                            if (isSildeDown) {
                                if (mScrollY - iv_day_sign_img.getBottom() / 3 > 0) {
                                    smoothScrollToLocation(layout_today_title.getTop() + txt_day_sign_top.getTop() - top_layout.getMeasuredHeight());
                                }
                            } else {
                                if (Math.abs(layout_today_title.getBottom() - mScrollY) > iv_day_sign_img.getBottom() / 3) {
                                    smoothScrollToLocation(0);
                                }
                            }
                            return;
                        }
                        mHandler.sendEmptyMessageDelayed(REQUESTCODE, 100);
                    }
                    break;
            }
        }
    };

    /**
     * 获取日签
     */
    @Override
    public void onDaySign(DaySignInfo info) {
        try {
            if (info.getErrCode() == 0) {
                DaySignInfo.ResponseBean bean = info.getResponse();
                if (bean == null) {
                    return;
                }
                this.signInfo = bean;
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) iv_day_sign_img.getLayoutParams();
                lp.height = DensityUtil.getScreenWidth(getActivity()) / 9 * 8;
                lp.width = DensityUtil.getScreenWidth(getActivity());
                iv_day_sign_img.setLayoutParams(lp);
                iv_day_sign_img.setScaleType(ImageView.ScaleType.FIT_XY);
                //总layout
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_data.getLayoutParams();
                layoutParams.height = lp.height + getActivity().getResources().getDimensionPixelSize(R.dimen.dd_dimen_56px);
                layout_data.setLayoutParams(layoutParams);
                //iv_white_data
                RelativeLayout.LayoutParams iv_white_lp = (RelativeLayout.LayoutParams) iv_white_data.getLayoutParams();
                iv_white_lp.topMargin = lp.height - getActivity().getResources().getDimensionPixelSize(R.dimen.dd_dimen_128px);
                iv_white_data.setLayoutParams(iv_white_lp);
                //img
                GlideUtils.loadImageView(getActivity(), iv_day_sign_img, bean.getImgUrl());
                iv_day_sign_img.setLayoutParams(lp);
                //title
                txt_day_sign_title.setText(bean.getImgExplain());
                //content
                txt_day_sign_content.setText(bean.getDailyContent());
                // 点赞
                praise_num.setText(presenter.formatNum(bean.getIkeCount()));
                iv_praise.setImageResource(bean.getIsLike() == 0 ? R.drawable.praise_gray_sign_icon : R.drawable.praise_red_sign_icon);
                String dailyDate = bean.getDailyDate();
                if (!TextUtils.isEmpty(dailyDate)) {
                    Date date = DateUtils.parseDate(DateUtils.YYYY_MM_DD, dailyDate);
                    String year_month = DateUtils.formatDate("yyyy年MM月", date);
                    String share_data = DateUtils.formatDate("yyyy年MM月dd日", date);
                    String day = DateUtils.formatDate("dd", date);
                    String week = DateUtils.formatDate("E", date);
                    //data
                    date_content.setText(year_month + "/" + week);
                    //share_data
                    txt_share_data.setText(share_data + " " + week);
                    //img
                    iv_white_data.setImageResource(FileUtils.getResource(getContext(), "date_white_" + day));
                    iv_black_data.setImageResource(FileUtils.getResource(getContext(), "date_black_" + day));
                }
            } else {
                toast(info.getErrMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文章详情
     *
     * @param responseBeanList
     */
    @Override
    public void onArticleDetail(List<ArticleItem> responseBeanList) {
        if (responseBeanList == null) {
            return;
        }
        if (isLoadMore) {//加载更多
            if (responseBeanList.size() < pageSize) {
                refreshLayout.finishLoadmoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadmore();
            }
            this.mArticleItemList.addAll(responseBeanList);
        } else {//刷新
            refreshLayout.finishRefresh();
            if (getActivity() != null && pageIndex == 1 && !isHeaderRefresh) {
                ((BaseActivity) getActivity()).showLoading(false);
            }
            this.mArticleItemList.clear();
            this.mArticleItemList.addAll(responseBeanList);
        }
        todayAdapter.notifyDataSetChanged();
        //今日推荐在顶部位置
        final int topLocation = layout_today_title.getTop() + txt_day_sign_top.getTop() - top_layout.getMeasuredHeight();
        if (!isLoadMore) {
            if (nested_scroll_view.getScrollY() != topLocation && !isFirstEnter) {
                smoothScrollToLocation(topLocation);
            }
            if (!isFirstEnter) {
                toast("已为你推荐更多新内容");
            }
            isFirstEnter = false;
        }
    }

    /**
     * 平滑 慢速 动画
     */
    public void smoothScrollToLocation(int location) {
        ObjectAnimator yTranslate = ObjectAnimator.ofInt(nested_scroll_view, "scrollY", location);
        AnimatorSet animators = new AnimatorSet();
        animators.setDuration(800L);
        animators.playSequentially(yTranslate);
        animators.start();
    }

    /**
     * 日签点赞
     *
     * @param info
     */
    @Override
    public void onPraiseDaySignSuccess(INetBean info) {
        if (info.getErrCode() == 0) {
            if (signInfo != null) {
                int praiseNum = signInfo.getIkeCount();
                if (signInfo.getIsLike() == 0) {//点赞成功
                    praiseNum++;
                    signInfo.setIsLike(1);
                    praise_num.setText(presenter.formatNum(praiseNum));
                    iv_praise.setImageResource(R.drawable.praise_red_sign_icon);
                } else {//取消点赞成功
                    praiseNum--;
                    signInfo.setIsLike(0);
                    praise_num.setText(presenter.formatNum(praiseNum));
                    iv_praise.setImageResource(R.drawable.praise_gray_sign_icon);
                }
                signInfo.setIkeCount(praiseNum);
            }
        } else {
            toast(info.getErrMsg());
        }
    }
}
